package com.epam.training.concurrency.second.task5;

import java.util.Iterator;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 
 * Test bank.transfer method
 * 
 * @author bogdan
 *
 */
public class Test {

	private Test() {

	}

	private static Bank bank;

	/**
	 * generate account for bank
	 * 
	 * @param accountNumber
	 */
	public static void generateAccounts(int accountNumber) {
		Random random = new Random();

		for (int i = 0; i < accountNumber; i++) {
			bank.add(new Account(random.nextInt(1000000)));
		}
	}

	/**
	 * Calculate full accounts sum
	 * 
	 * @return
	 */
	public static int calculateSum() {
		Iterator<Account> iterator = bank.iterator();

		int sum = 0;

		while (iterator.hasNext()) {
			sum += iterator.next().checkAccount();
		}

		return sum;
	}

	/**
	 * 
	 * @param threadNumber
	 */
	public static void generateThreads(int threadNumber) {
		final int randomLimits = 100;
		final int amountLimit = 1000;

		Random random = new Random();
		TestThread[] threads = new TestThread[threadNumber];

		for (int i = 0; i < threadNumber; i++) {
			threads[i] = new TestThread(bank, bank.get(random
					.nextInt(randomLimits)), bank.get(random
					.nextInt(randomLimits)), random.nextInt(amountLimit));
			threads[i].start();
		}

		for (int i = 0; i < threadNumber; i++) {
			try {
				threads[i].join();
			} catch (InterruptedException e) {
				Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null,
						e);
			}
		}
	}

	/**
	 * Main method of test class
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		bank = new Bank();

		generateAccounts(1000);

		int sum1 = calculateSum();

		generateThreads(1000);

		int sum2 = calculateSum();

		Logger.getLogger(Test.class.getName())
				.log(Level.INFO,
						"Is it transfers correct? – "
								+ ((sum1 == sum2) ? "Yes" : "No"));

	}

}
